// pages/orderlist/neworder/neworder.js
var actionType;
var app = getApp();
var user_note;
var goodsNames;
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    actionType = ''
    if (options.action) {
      actionType = options.action;
    }
    user_note = '';
    goodsNames = '';
    var ordersinfo = JSON.parse(options.orderinfos);
    var totalprice = app.keepTwoDecimalFull(ordersinfo.cartPriceInfo.total_fee);
    var totalcount = ordersinfo.cartGoodsTotalNum;
    var discount_fee = app.keepTwoDecimalFull(ordersinfo.cartPriceInfo.goods_fee);
    var address = ordersinfo.address;
    if (address == null) {
      address = {
        address_id: ''
      };
    }
    var invoiceinfo = ordersinfo.extend;
    var invoicetype = '0';
    var invoiceName;
    var invoiceCode;
    if (invoiceinfo == '') {
      invoiceName = '';
      invoiceCode = '';
    }
    else {
      if (invoiceinfo.indexOf(':') >= 0) {
        var tmparr = invoiceinfo.split(':');
        if (tmparr[0] == '个人') {
          invoiceName = tmparr[2];
          invoiceCode = ''
        }
        else {
          invoiceName = tmparr[0]
          invoiceCode = tmparr[1];
        }
      }
      else {
        invoiceName = '';
        invoiceCode = '';
      }
    }
    if (invoiceName == undefined) {
      invoiceName = '';
    }
    if (invoiceCode == undefined) {
      invoiceCode = '';
    }
    var shippinglist = ordersinfo.shippingList;
    var goods = [];
    var goodsids = [];
    var goodsnums = [];
    var speckeys = [];
    var all_goods = [];
    for (var i = 0; i < ordersinfo.cartList.length; i++) {
      var goodsinfo = {};
      goodsinfo.name = ordersinfo.cartList[i].goods_name;
      goodsinfo.icon = app.globalData.webUrl + ordersinfo.cartList[i].goods.original_img;
      goodsinfo.goodsid = ordersinfo.cartList[i].goods_id;
      goodsinfo.price = app.keepTwoDecimalFull(ordersinfo.cartList[i].member_goods_price);
      goodsinfo.buycount = ordersinfo.cartList[i].goods_num;

      all_goods.push(goodsinfo.name);
      var standard = [];
      if (ordersinfo.cartList[i].spec_key_name) {
        if (ordersinfo.cartList[i].spec_key_name != '') {
          standard = ordersinfo.cartList[i].spec_key_name.split(' ');
          for (var j = 0; j < standard.length; j++) {
            standard[j] = standard[j].split(':')[1];
          }
        }
      }
      goodsinfo.standard = standard;
      goodsids.push(goodsinfo.goodsid);
      goodsnums.push(goodsinfo.buycount);
      speckeys.push(ordersinfo.cartList[i].item_id);
      goods.push(goodsinfo);
    }
    goodsNames = all_goods.join(',');
    var able_coupon_count = 0;
    var couponCanUseList = [];
    for (var i = 0; i < ordersinfo.userCartCouponList.length; i++) {
      if (ordersinfo.userCartCouponList[i].coupon.able.toString() == '1') {
        able_coupon_count++;
        couponCanUseList.push(ordersinfo.userCartCouponList[i]);
      }
    }
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        var t_width1 = 70;
        var t_width2 = res.windowWidth * 0.95 - t_width1;
        that.setData({
          t_width1: t_width1,
          t_width2: t_width2
        });
      },
    });
    that.setData({
      invoiceshow: false,
      invoice: '不开发票',
      invoicetype: invoicetype,
      invoiceName: invoiceName,
      invoiceCode: invoiceCode,
      address: address,
      shippinglist: shippinglist,
      shippingname: '未选择',
      shippingcode: '',
      orders: goods,
      goods_ids: goodsids.join(','),
      goods_nums: goodsnums.join(','),
      spec_keys: speckeys.join(','),
      totalprice: totalprice,
      totalcount: totalcount,
      disfee: discount_fee,
      expressfee: 0.00,
      goodstotalprice: totalprice,
      totalcoupon: able_coupon_count,
      couponCanUseList: couponCanUseList,
      couponnote: '',
      couponid: ''
    });

    that.setData({ shippingcode: that.data.shippinglist[0].code, shippingname: that.data.shippinglist[0].name });

    app.showLoading();
    this.updateOrder(address.address_id, 'address');
  },
  updateOrder: function (dvalue, dtype) {
    var params = {
      address_id: this.data.address.address_id,
      coupon_id: this.data.couponid,
      goods_id: this.data.goods_ids,
      goods_num: this.data.goods_nums,
      item_id: this.data.spec_keys,
      shipping_code: this.data.shippingcode,
      act: '',// 下单参数 submit_order
      action: actionType// buy_now
    };
    var url = '/index.php/api/Cart/cart3';
    if (dtype == 'address') {
      params.address_id = dvalue;
    }
    else if (dtype == 'coupon') {
      params.coupon_id = dvalue;
    }
    else if (dtype == 'shipping') {
      params.shipping_code = dvalue;
    }
    app.request(url,params).then(this.updateOrderCallBack.bind(this));
  },
  updateOrderCallBack: function (res) {
    app.hideLoading();
    if (res.status != 'ok' && res.status != '1') {
      wx.showToast({
        icon: "none",
        title: res.msg,
      });
      return;
    }
    this.setData({
      expressfee: app.keepTwoDecimalFull(res.result.postFee),
      disfee: app.keepTwoDecimalFull(res.result.couponFee),
      goodstotalprice: app.keepTwoDecimalFull(res.result.goodsFee),
      totalprice: app.keepTwoDecimalFull(res.result.payables),
      activityfee: app.keepTwoDecimalFull(res.result.order_prom_amount)
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.checkAddress();
    this.checkCoupon();
  },
  checkAddress() {
    var status = app.globalData.address.status;
    if (status < 0) {
      return;
    };
    var old_address = this.data.address.address_id;
    var new_address = app.globalData.address.value.addressid;
    console.log(old_address, new_address);
    if (old_address.toString() == new_address.toString()) {
      app.globalData.address.status = -1;
      app.globalData.address.value = null;
      return;
    }

    var address = this.data.address;
    address.address_id = app.globalData.address.value.addressid;
    address.consignee = app.globalData.address.value.name;
    address.mobile = app.globalData.address.value.phone;
    address.address = app.globalData.address.value.address;
    this.setData({
      address: address
    });
    app.globalData.address.status = -1;
    app.globalData.address.value = null;

    app.showLoading();
    this.updateOrder(this.data.address.address_id, "address");
  },
  checkCoupon: function () {
    if (app.globalData.coupon.status < 0) {
      this.setData({
        couponnote: '',
        couponid: ''
      });
      return;
    }
    var coupon = app.globalData.coupon.value;
    var notes = coupon.value + '元（' + coupon.name + '，满' + coupon.note + '）';
    this.setData({
      couponnote: notes,
      couponid: coupon.couponid
    });
    app.globalData.coupon.status = -1;
    app.globalData.coupon.value = null;

    app.showLoading();
    this.updateOrder(this.data.couponid, "coupon");
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.shareToIndex();
  },
  selecetAddress: function () {
    wx.navigateTo({
      url: '../../my/address/address?dealtype=selected',
    });
  },
  selectedCoupon: function () {
    if (this.data.totalcoupon <= 0) {
      return;
    }
    wx.navigateTo({
      url: '../../my/coupon/coupon?dealtype=selected&money=' + this.data.goodstotalprice + '&couponlist=' + JSON.stringify(this.data.couponCanUseList),
    });
  },
  submitOrder: function () {
    if (this.data.shippingcode == '') {
      wx.showToast({
        image: '../../imgs/tips.png',
        title: '请选择物流快递',
      });
      return;
    }
    if (this.data.address.address_id == '') {
      wx.showToast({
        image: '../../imgs/tips.png',
        title: '请填写收货地址',
      });
      return;
    }
    app.showLoading();
    var invoice_title = '';
    if (this.data.invoicetype == '1') {
      if (this.data.invoiceName == '') {
        wx.showToast({
          image: '../../imgs/tips.png',
          title: '发票信息不完整',
        });
        return;
      }
      invoice_title = '个人:' + this.data.invoiceName;
    }
    else if (this.data.invoicetype == '2') {
      if (this.data.invoiceName == '' || this.data.invoiceCode == '') {
        wx.showToast({
          image: '../../imgs/tips.png',
          title: '发票信息不完整',
        });
        return;
      }
      invoice_title = this.data.invoiceName + ':' + this.data.invoiceCode;
    }
    var params = {
      address_id: this.data.address.address_id,
      coupon_id: this.data.couponid,
      goods_id: this.data.goods_ids,
      goods_num: this.data.goods_nums,
      item_id: this.data.spec_keys,
      invoice_title: invoice_title,
      user_note: user_note,
      shipping_code: this.data.shippingcode,
      act: 'submit_order',// 下单参数 
      action: actionType // buy_now
    };
    var url = '/index.php/api/Cart/cart3';
    app.request(url,params).then(this.submitOrderCallBack.bind(this));
  },
  submitOrderCallBack: function (res) {
    app.hideLoading();
    console.log(goodsNames);
    if (res.status == 'ok') {
      var payFee = parseFloat(res.result.order_amount);
      if(payFee <= 0){
        wx.redirectTo({
          url: '../orderlist?ordertype=3&ordercode=WAITSEND',
        });
      }
      else{
        wx.redirectTo({
          url: '../payorder/payorder?order=' + JSON.stringify(res.result) + '&goodsnames=' + goodsNames + '&entry=neworder',
        });
      }
    }
    else {
      wx.showToast({
        icon: 'none',
        title: res.msg,
      });
    }
  },
  userNoteInput: function (event) {
    user_note = event.detail.value;
  },
  selectedShipping: function () {
    var that = this;
    var ships = [];
    for (var i = 0; i < that.data.shippinglist.length;i++){
      ships.push(that.data.shippinglist[i].name);
    }
    wx.showActionSheet({
      itemList: ships,
      success: function (res) {
        that.setData({
          shippingname: that.data.shippinglist[res.tapIndex].name,
          shippingcode: that.data.shippinglist[res.tapIndex].code
        });
        app.showLoading();
        that.updateOrder(that.data.shippingcode, 'shipping');
      }
    });
  },
  radioChange: function (event) {
    this.setData({
      invoicetype: event.detail.value
    });
  },
  needInvoiceYesOrNo: function (event) {
    var itype, invoice;
    if (event.detail.value == '1') {
      itype = '0';
      invoice = '不开发票';
    }
    else {
      if (this.data.invoiceCode == '') {
        itype = '1';
      }
      else {
        itype = '2';
      }
      invoice = '开发票';
    }
    this.setData({
      invoicetype: itype,
      invoice: invoice
    });
  },
  selectedInvoice: function (event) {
    var invoiceshow = !this.data.invoiceshow;
    this.setData({
      invoiceshow: invoiceshow
    });
  },
  invoiceInput: function (event) {
    var intype = event.currentTarget.dataset.intype;
    if (intype == '1' || intype == '2') {
      this.setData({
        invoiceName: event.detail.value
      });
    }
    else if (intype == '3') {
      this.setData({
        invoiceCode: event.detail.value
      });
    }
  },
  doNothing: function () { },
  confirmInvoice: function () {
    var tmpName, tmpTitle, tmpCode;
    if (this.data.invoicetype == '1') {
      if (this.data.invoiceName == '') {
        wx.showToast({
          title: '发票信息不完整',
          icon: 'none'
        });
        return;
      }
      tmpName = this.data.invoiceName;
      tmpTitle = '个人';
      tmpCode = '';
    }
    else if (this.data.invoicetype == '2') {
      if (this.data.invoiceName == '' || this.data.invoiceCode == '') {
        wx.showToast({
          title: '发票信息不完整',
          icon: 'none'
        });
        return;
      }
      tmpName = '';
      tmpTitle = this.data.invoiceName;
      tmpCode = this.data.invoiceCode;
    }
    else {
      wx.showToast({
        title: '发票信息不完整',
        icon: 'none'
      });
      return;
    }
    var url = '/index.php/api/Cart/save_invoice';
    var params = {
      invoice_title: tmpTitle,
      taxpayer: tmpCode,
      realname: tmpName
    };
    app.request(url, params).then(this.confirmInvoiceCallBack.bind(this));
  },
  confirmInvoiceCallBack: function (res) {
    console.log(res);
    this.setData({
      invoiceshow:false
    });
  }
})